#include "time.h"
#include "cpu_instr.h"
#include "types.h"
#include "irq.h"
#include "os_cfg.h"
#include "task.h"

static uint32_t sys_tick;
static void     pit_init(void)
{
    // 1000/PIT_OSC_FREQ, OS_TICKS_MS / (1000/PIT_OSC_FREQ)
    uint32_t reload_count = PIT_OSC_FREQ * OS_TICKS_MS / 1000;
    // 向 PIT 发送命令
    outb(PIT_COMMAND_PORT, PIT_CHANNEL0 | PIT_MODE_LOHI | PIT_MODE_3);    // count in 16bit mode
    // 向 PIT 发送频率
    outb(PIT_CHANNEL0_DATA_PORT, reload_count & 0xFF);           // send frquency low byte
    outb(PIT_CHANNEL0_DATA_PORT, (reload_count >> 8) & 0xFF);    // send frquency high byte

    irq_install(IRQ32_TIME, (irq_handler_t)exception_handler_time);
    irq_enable(IRQ32_TIME);
}
void time_init(void)
{
    sys_tick = 0;
    pit_init();
}
void do_handler_time(exception_frame_t *frame)
{
    sys_tick++;
    pic_send_eoi(IRQ32_TIME);
    task_time_tick();
}